import time
import psutil
import os

# 获取当前进程的内存使用情况
def get_current_memory_usage():
    """获取当前进程的内存使用情况（MB）"""
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    return mem_info.rss / 1024 / 1024  # 转换为MB

# 获取系统指标
def get_metrics():
    """获取系统指标信息"""
    try:
        # 系统基本信息
        metrics = {
            "timestamp": time.time(),
            "uptime": time.time() - psutil.boot_time(),
            "memory_usage": get_current_memory_usage(),
            "cpu_percent": psutil.cpu_percent(interval=0.1),
            "disk_usage": {
                "total": psutil.disk_usage('/').total / 1024 / 1024 / 1024,  # 转换为GB
                "used": psutil.disk_usage('/').used / 1024 / 1024 / 1024,
                "free": psutil.disk_usage('/').free / 1024 / 1024 / 1024,
                "percent": psutil.disk_usage('/').percent
            },
            "network": {
                "bytes_sent": psutil.net_io_counters().bytes_sent,
                "bytes_recv": psutil.net_io_counters().bytes_recv
            }
        }
        return metrics
    except Exception as e:
        # 发生错误时返回基本信息
        return {
            "timestamp": time.time(),
            "error": str(e),
            "metrics_available": False
        }

# 获取Python版本信息
def get_python_version():
    """获取Python版本信息"""
    import sys
    return f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"

# 检查数据库健康状态
def check_database_health():
    """检查数据库健康状态"""
    try:
        from backend.database.db import db_manager
        # 检查数据库连接是否正常
        connection = db_manager.get_connection()
        if connection:
            return {
                "status": "ok",
                "type": "postgresql" if hasattr(db_manager, "_use_in_memory_mode") and not db_manager._use_in_memory_mode else "in_memory"
            }
        else:
            return {
                "status": "error",
                "message": "数据库连接失败"
            }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }

# 检查LLM健康状态
def check_llm_health():
    """检查LLM健康状态"""
    try:
        from backend.llm import llm_manager
        # 检查LLM是否可用
        active_provider = llm_manager.get_active_provider()
        return {
            "status": "ok",
            "active_provider": active_provider
        }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }

# 检查RAG健康状态
def check_rag_health():
    """检查RAG健康状态"""
    try:
        from backend.rag.retriever import rag_manager
        # 检查RAG组件是否正常
        stats = rag_manager.get_rag_stats()
        return {
            "status": "ok",
            "document_count": stats.get("document_count", 0),
            "chunk_count": stats.get("chunk_count", 0)
        }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }

# 检查工具健康状态
def check_tools_health():
    """检查工具健康状态"""
    try:
        from backend.tools.tool_caller import tool_caller
        # 检查工具调用器是否正常
        available_tools = tool_caller.get_available_tools()
        return {
            "status": "ok",
            "available_tools": available_tools
        }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }

# 获取清理后的配置信息
def get_sanitized_config():
    """获取清理后的配置信息（移除敏感信息）"""
    try:
        from backend.common.config import config_manager
        # 创建配置的副本并移除敏感信息
        sanitized = {
            "api": {
                "host": config_manager.api.host,
                "port": config_manager.api.port,
                "workers": config_manager.api.workers,
                "debug": config_manager.api.debug,
                "version": config_manager.api.version
            },
            "database": {
                "host": config_manager.db.host,
                "port": config_manager.db.port,
                "dbname": config_manager.db.dbname,
                "user": "******" if config_manager.db.user else ""
            },
            "model": {
                "name": config_manager.model.name,
                "quantized": config_manager.model.quantized,
                "max_new_tokens": config_manager.model.max_new_tokens,
                "temperature": config_manager.model.temperature
            },
            "rag": {
                "enabled": config_manager.rag.enabled,
                "top_k": config_manager.rag.top_k,
                "chunk_size": config_manager.rag.chunk_size
            },
            "tools": {
                "enabled": config_manager.tools.enabled,
                "allowed_tools": config_manager.tools.allowed_tools
            },
            "learning": {
                "enabled": config_manager.learning.enabled
            }
        }
        return sanitized
    except Exception as e:
        return {
            "error": str(e),
            "config_available": False
        }